<template>
  <!-- 班组表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="800px"
      draggable
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" class="isDeafutl">
        <el-row>
          <el-col :span="12">
            <el-form-item label="班组编号" prop="crewCode">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.crewCode"
                placeholder="请输入班组编号"
                clearable
              />

              <span v-else>{{ formData.crewCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班组名称" prop="crewName">
              <el-input
                v-if="!props.isReadonly"
                v-model="formData.crewName"
                placeholder="请输入班组名称"
                clearable
              />

              <span v-else>{{ formData.crewName }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工厂" prop="plantCode">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.plantCode"
                placeholder="请选择所在工厂"
                clearable
                style="width: 100%"
                @change="changePlant"
                filterable
              >
                <el-option
                  v-for="item in plantList"
                  :key="item.id"
                  :label="item.organizationCode"
                  :value="item.organizationCode"
                />
              </el-select>

              <span v-else>{{ formData.plantCode }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!--            <el-form-item label="工作中心" prop="workCenterCode">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.workCenterCode"
                placeholder="请选择工作中心"
                clearable
                style="width: 300px"
                :disabled="formData.plantId === ''"
                filterable
              >
                <el-option
                  v-for="item in workCenterValue"
                  :key="item.id"
                  :label="`${item.workshopCode}-${item.workshopName}`"
                  :value="item.workshopCode"
                />
              </el-select>

              <span v-else>{{ formData.workCenterCode }}</span>
            </el-form-item>-->
            <el-form-item label="车间" prop="shopFloorId">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.shopFloorId"
                placeholder="请输入车间"
                clearable
                style="width: 300px"
                @change="changeshopFloor"
                filterable
              >
                <el-option
                  v-for="item in shopFloorValue"
                  :key="item.id"
                  :label="`${item.shopFloorCode}-${item.shopFloorName}`"
                  :value="item.id"
                />
              </el-select>
              <span v-else>{{ formData.shopFloorCode }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="班组类型" prop="crewType">
              <el-select
                v-if="!props.isReadonly"
                v-model="formData.crewType"
                placeholder="请选择班组类型"
                clearable
                style="width: 300px"
              >
                <el-option
                  v-for="item in dictionaryStore.filterDictList('CrewType')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>

              <span v-else>{{
                useDictionary("CrewType", formData.crewType)
              }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="enabled">
              <el-radio-group
                v-model="formData.enabled"
                v-if="!props.isReadonly"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
              <span v-else>{{ formData.enabled == 1 ? "启用" : "停用" }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            clearable
          />

          <span v-else>{{ formData.remarks }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useDictionary } from "@/utils/useTable";

defineOptions({
  name: "MESMESCREWADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

const rules = reactive({
  crewCode: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入班组编号",
      trigger: "blur",
    },
    { required: true, message: "请输入班组编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  crewName: [
    {
      required: true,
      pattern: "[^ \x20]+",
      message: "请输入班组名称",
      trigger: "blur",
    },
    { required: true, message: "请输入班组名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  crewType: [{ required: true, message: "请选择班组类型", trigger: "change" }],
  plantCode: [{ required: true, message: "请选择工厂编号", trigger: "change" }],
  shopFloorId: [
    { required: true, message: "请选择车间编号", trigger: "change" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData: any = reactive({
  id: "",
  crewCode: "",
  crewName: "",
  crewType: "",
  organizationId: "",
  organizationCode: "",
  plantId: "",
  plantCode: "",
  shopFloorId: "",
  shopFloorCode: "",
  shopFloorName: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        crewCode,
        crewName,
        crewType,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        shopFloorId,
        shopFloorCode,
        shopFloorName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      } = newVal;
      Object.assign(formData, {
        id,
        crewCode,
        crewName,
        crewType,
        organizationId,
        organizationCode,
        plantId,
        plantCode,
        shopFloorId,
        shopFloorCode,
        shopFloorName,
        version,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        enabled,
        deleted,
      });
      formData.crewType = String(formData.crewType);
      shopFloors();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();

  formData.id = "";
  formData.crewCode = "";
  formData.crewName = "";
  formData.crewType = "";
  formData.organizationId = "";
  formData.organizationCode = "";
  formData.plantId = "";
  formData.plantCode = "";
  formData.shopFloorId = "";
  formData.shopFloorCode = "";
  formData.shopFloorName = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  shopFloorValue.value = [];
}

const loading = ref(false);

/** 班组保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";

      await request({
        url: "/mes/mescrew/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 获取工厂列表
const plantList: any = ref([]);
const getPlantList = async () => {
  const res1 = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = res1.data;
};
// 根据工厂id 查询班次
const shopFloorValue: any = ref([]);
const shopFloors = async () => {
  if (formData.plantCode != "") {
    const res2: any = await request({
      url: `/mdm/mdmshopfloor/getList`,
      method: "post",
      data: { enabled: 1, plantId: formData.plantId },
    });
    shopFloorValue.value = res2.data;
  } else {
    shopFloorValue.value = [];
  }
};
//车间赋值
const changeshopFloor = (id: any) => {
  if (id) {
    formData.shopFloorId = id;
    shopFloorValue.value.forEach((item) => {
      if (item.id == id) {
        formData.shopFloorCode = item.shopFloorCode;
        formData.shopFloorName = item.shopFloorName;
      }
    });
  } else {
    formData.shopFloorId = "";
    formData.shopFloorCode = "";
    formData.shopFloorName = "";
    shopFloors();
  }
};
/** 选择工厂时触发 根据Code赋值Id*/

const changePlant = () => {
  formData.shopFloorCode = "";
  formData.shopFloorId = "";
  formData.shopFloorName = "";
  plantList.value.forEach((item: any) => {
    if (item.organizationCode == formData.plantCode) {
      formData.plantId = item.id;
    }
  });
  shopFloors();
};

// watch(
//   () => formData.plantCode,
//   (newVal: any) => {
//     if (formData.plantCode != "" && formData.id != "") {
//       formData.workCenterCode = "";
//       formData.workCenterId = "";
//     }
//     plantList.value.forEach((item: any) => {
//       if (item.organizationCode == formData.plantCode) {
//         formData.plantId = item.id;
//       }
//     });
//     workCenterList();
//   }
// );
/** 选择车间触发 根据Code赋值Id*/
watch(
  () => formData.shopFloorCode,
  (newVal: any) => {
    shopFloorValue.value.forEach((item: any) => {
      if (item.workshopCode == formData.shopFloorCode) {
        formData.shopFloorId = item.id;
      }
    });
  }
);
onMounted(() => {
  getPlantList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
<style lang="scss" scoped>
.isDeafutl {
  :deep(.el-form-item__label) {
    width: 110px !important;
  }
}
</style>
